// ###############################################
//
// AUTHOR: Nick LaPrell (http://nick.laprell.org)  
//
// Basic cookie functions for reading and writing
// to cookies.
//
// $.getCookie(cookieName)
//   Returns the value of the specified cookie.
//
// $.getValueFromCookie(cookie,key)
//   Returns the value of the given key for the
//   specified cookie.
//
// $.writeCookie(cookieName,cookieValue,options)
//   Writes a cookie with the given name and value.
//
// $.writeValueToCookie(cookie,key,value,options)
//   Writes the given key/value pair to the named 
//   cookie, delimited with an ampersand (&). If 
//   the given key already exists, its value is 
//   overwritten.
//
// $.removeKeyFromCookie(cookie,key)
//   Removes the given key and its value from the
//   specified cookie.
//
// $.removeCookie(cookie)
//   Writes an empty string to the given cookie
//   and sets its expiration to -1. 
//
// $.clearCookie(cookie)
//   Writes an empty string to the given cookie
//   without changing the expiration date, allowing
//   it to be written to again later.
//
// ###############################################

jqPlugins.cookie = true;

(function($){
  
  // Default options
  cOptions = {
    expires : 365,
    domain : '',
    URIEncode : false,
    secure : false,
    path : '/'
  }

  // Returns the cookie or null if it does not exist.
  $.getCookie = function(cookieName) {
    var value = null;
    if(document.cookie && document.cookie != ''){
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, cookieName.length + 1) == (cookieName + '=')) {
          value = decodeURIComponent(cookie.substring(cookieName.length + 1));
          break;
        }
      }
    }
    return value;
  }

  // Get the value of the specified key of the specified cookie.
  $.getValueFromCookie = function(cookie,key){
    var cookie = $.getCookie(cookie);
    if(!cookie){return null;}
    var nameValuePairs = cookie.split('&');
    var value = null;
    for(var k in nameValuePairs){
      if(!(k % 2)){
        if(nameValuePairs[k] == key){
          value = nameValuePairs[(parseInt(k)+1)];
        }
      }
    }
    return value;
  }
  
  // Write the defined value to the given cookie
  $.writeCookie = function(cookieName,cookieValue,options){
    // Combine defaults and passed options, if any
    var options = typeof options != 'undefined' ? $.extend(cOptions, options) : cOptions;
    // Set cookie attributes based on options
    var path = '; path=' + (options.path);
    var domain = '; domain=' + (options.domain);
    var secure = options.secure ? '; secure' : '';
    var cookieValue = options.URIEncode ? encodeURIComponent(cookieValue) : cookieValue;
    var date;
    // Set expiration
    if (typeof options.expires == 'number') {
      date = new Date();
      date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
    } else {
      date = options.expires;
    }
    var expires = '; expires=' + date.toUTCString();
    // Write the cookie
    document.cookie = [cookieName, '=', cookieValue, expires, path, domain, secure].join('');
  }
  
  // Write the given name/value pair to the defined cookie. If the given key exists, its value is replaced.
  $.writeValueToCookie = function(cookie,key,value,options){
    // Combine defaults and passed options, if any
    var options = typeof options != 'undefined' ? $.extend(cOptions, options) : cOptions;
    var newCookieValue = '';
    var existingValue = $.getValueFromCookie(cookie,key);
    var existingCookie = $.getCookie(cookie);
    if(existingValue){
      // Find the existing name/value pair and replace the value
      var nameValuePairs = existingCookie.split('&');
      for(var k in nameValuePairs){
        if(!(k % 2)){
          if(nameValuePairs[k] == key){
            nameValuePairs[(parseInt(k)+1)] = value;
          }
        }
        if(newCookieValue){newCookieValue +='&';}
        if(nameValuePairs[k]){newCookieValue += nameValuePairs[k];}
      }
    } else if(existingCookie) {
      // Append the name/value pair to the existing cookie
      newCookieValue = existingCookie + '&' + key + '&' + value;
    } else {
      newCookieValue = key + '&' + value;
    }
    $.writeCookie(cookie,newCookieValue,options);
  }

  $.removeKeyFromCookie = function(cookie,key){
    var cookieString = $.getCookie(cookie);
    if(!cookieString){return;}
    if($.getValueFromCookie(cookie,key) == null){return;}
    var value = $.getValueFromCookie(cookie,key);
    var nameValuePairs = cookieString.split('&');
    // Remove the key/value pair
    if(!Array.indexOf){
      // Stupid IE 6 doesn't like indexOf
      for (var i in nameValuePairs) {
        if (nameValuePairs[i] == key) {
          var removeKey = i;
          break;
        }
      }
    } else {
      var removeKey = nameValuePairs.indexOf(key);
    }
    nameValuePairs.splice(removeKey, 1);
    nameValuePairs.splice(removeKey, 1);

    // REMOVE EMPTIES - BUG WORK AROUND
    var newCookie = Array();
    for(var i in nameValuePairs){
      if(nameValuePairs[i] != ''){newCookie.push(nameValuePairs[i]);}
    }

    $.writeCookie(cookie,newCookie.join('&'));
  }

  $.removeCookie = function(cookie){
    $.writeCookie(cookie,'',{expires:-1});
  }

  $.clearCookie = function(cookie){
    $.writeCookie(cookie,'');
  }
  
})(jQuery);